"""
Case Type   : GSC功能模块
Case Name   : gs_gsc_clean清除当前连接库的缓存信息
Create At   : 2022/05/10
Owner       : opentestcase024
Description :
    1、打开gsc开关;
    2、重启数据库生效;
    3、创建数据库;
    4、创建表并查询;
    5、查看syscache占用情况;
    5.1、查看gs_gsc_memory_detail占用情况;
    5.2、查看gs_gsc_dbstat_info占用情况;
    5.3、查看gs_gsc_table_detail占用情况;
    5.4、查看gs_gsc_catalog_detail占用情况;
    6、连接指定库，删除该库缓存信息;
    7、查看syscache占用情况;
    7.1、查看gs_gsc_memory_detail占用情况;
    7.2、查看gs_gsc_dbstat_info占用情况;
    7.3、查看gs_gsc_table_detail占用情况;
    7.4、查看gs_gsc_catalog_detail占用情况;
Expect      :
    1、打开gsc开关; 修改成功
    2、重启数据库生效; 重启成功
    3、创建数据库; 创建成功
    4、创建表并查询; 操作成功
    5.1、查看gs_gsc_memory_detail占用情况; 指定库查询结果等于1
    5.2、查看gs_gsc_dbstat_info占用情况; 查询结果包括0库和指定库2个
    5.3、查看gs_gsc_table_detail占用情况; 查询结果包括0库和指定库2个
    5.4、查看gs_gsc_catalog_detail占用情况; 查询结果包括0库和指定库2个
    6、连接指定库，删除该库缓存信息; 删除成功
    7、查看syscache占用情况; 缓存信息正确
    7.1、查看gs_gsc_memory_detail占用情况; 指定库结果等于1，每个库查询结果小于步骤5
    7.2、查看gs_gsc_dbstat_info占用情况; 查询结果包含0库和指定库，每个库查询结果小于步骤5
    7.3、查看gs_gsc_table_detail占用情况; 查询结果只有0库或者包含0库和指定库，每个库查询结果小于步骤5
    7.4、查看gs_gsc_catalog_detail占用情况; 查询结果包含0库和指定库，每个库查询结果小于步骤5
History     :
    Modified by peilinqian at 2025/1/21:teardown增加集群主备恢复动作，以防对其他用例产生影响
    modified by opentestcase024 2023-4-14：进行clean后，后台又快速进行部分缓存，优化用例
"""
import os
import time
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class GscTestCase(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info("----this is setup----")
        self.log.info(f'----{os.path.basename(__file__)}:start----')
        self.db_name = 'db_gsc0039'
        self.tb_name = 'tb_gsc0039'
        self.com = Common()
        self.constant = Constant()
        self.sh = CommonSH('PrimaryDbUser')

        step_txt = '----step0:查看数据库状态是否正常;----'
        self.log.info(step_txt)
        status_result = self.sh.get_db_cluster_status('status')
        self.assertTrue(status_result, '执行失败:' + step_txt)
        step_txt = '----step0:查看enable_global_syscache初始配置值;----'
        self.log.info(step_txt)
        self.init_para1 = self.com.show_param("enable_global_syscache")

    def test_main(self):
        if self.init_para1 == 'off':
            step_txt = '----step1:打开gsc开关; expect:修改成功----'
            self.log.info(step_txt)
            result = self.sh.execute_gsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           f"enable_global_syscache= on")
            self.assertTrue(result, '执行失败:' + step_txt)

            step_txt = '----step2:重启数据库生效; expect:重启成功----'
            self.log.info(step_txt)
            restart = self.sh.restart_db_cluster()
            self.assertTrue(restart, '执行失败:' + step_txt)
            self.is_reset_para = True
        else:
            step_txt = '----gsc开关设置正常，跳过step1、step2----'
            self.log.info(step_txt)
            self.is_reset_para = False

        step_txt = f'----step3:创建数据库; expect:创建成功----'
        self.log.info(step_txt)
        create_db = f'drop database if exists {self.db_name};' \
            f'create database {self.db_name};'
        create_result = self.sh.execut_db_sql(create_db)
        self.log.info(create_result)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, create_result,
                      '执行失败:' + step_txt)

        step_txt = '----step4:创建表并查询; expect:操作成功----'
        self.log.info(step_txt)
        create_tb_sql = f"create table {self.tb_name} " \
            f"(c_integer integer,c_tinyint tinyint," \
            f"c_smallint smallint,c_binary_integer binary_integer," \
            f"c_bigint bigint,c_numeric numeric(10,4)," \
            f"c_number number(10,4),c_smallserial smallserial);" \
            f"select * from {self.tb_name};"
        create_result = self.sh.execut_db_sql(create_tb_sql,
                                              dbname=f'{self.db_name}')
        self.log.info(create_result)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, create_result,
                      '执行失败:' + step_txt)
        self.assertIn('0 rows', create_result, '执行失败:' + step_txt)

        time.sleep(5)

        step_txt = '----step5:查看syscache占用情况; expect:缓存信息正确----'
        self.log.info(step_txt)
        db_oid = f"(select cast((select oid from pg_database where " \
            f"datname = '{self.db_name}') as text))"
        check_sql1 = f"select * from gs_gsc_memory_detail where " \
            f"db_id ={db_oid};"
        check_sql2 = f"select database_id,total_memory,tup_count,rel_count," \
            f"database_name from gs_gsc_dbstat_info({db_oid}); "
        check_sql3 = f"select database_oid,count(*) from " \
            f"gs_gsc_table_detail({db_oid}) group by database_oid;"
        check_sql4 = f"select database_id,count(*) from " \
            f"gs_gsc_catalog_detail({db_oid}) group by database_id;"

        step_txt = '----step5.1:查看gs_gsc_memory_detail占用情况; ' \
                   'expect:指定库查询结果等于1----'
        self.log.info(step_txt)
        check_result5_1 = self.check_db_cache(check_sql1)
        check_db_list5_1 = check_result5_1[0]
        check_db_cache5_1 = check_result5_1[1]
        self.assertEqual(1, len(check_db_list5_1), '执行失败:' + step_txt)

        step_txt = '----step5.2:查看gs_gsc_dbstat_info占用情况; ' \
                   'expect:查询结果包括0库和指定库2个----'
        self.log.info(step_txt)
        check_result5_2 = self.check_db_cache(check_sql2)
        check_db_list5_2 = check_result5_2[0]
        check_db_cache5_2 = check_result5_2[1]
        self.assertEqual(2, len(check_db_list5_2), '执行失败:' + step_txt)

        step_txt = '----step5.3:查看gs_gsc_table_detail占用情况; ' \
                   'expect:查询结果包括0库和指定库2个----'
        self.log.info(step_txt)
        check_result5_3 = self.check_db_cache(check_sql3)
        check_db_list5_3 = check_result5_3[0]
        check_db_cache5_3 = check_result5_3[1]
        self.assertEqual(2, len(check_db_list5_3), '执行失败:' + step_txt)

        step_txt = '----step5.4:查看gs_gsc_catalog_detail占用情况; ' \
                   'expect:查询结果包括0库和指定库2个----'
        self.log.info(step_txt)
        check_result5_4 = self.check_db_cache(check_sql4)
        check_db_list5_4 = check_result5_4[0]
        check_db_cache5_4 = check_result5_4[1]
        self.assertEqual(2, len(check_db_list5_4), '执行失败:' + step_txt)

        step_txt = '----step6:连接指定库，删除该库缓存信息; expect:删除成功----'
        self.log.info(step_txt)
        clean_sql = f"select * from gs_gsc_clean({db_oid});"
        clean_result = self.sh.execut_db_sql(clean_sql,
                                             dbname=f'{self.db_name}')
        self.log.info(clean_result)
        self.assertEqual(clean_result.splitlines()[-2].strip().lower(), 't',
                         '执行失败:' + step_txt)

        step_txt = '----step7:查看syscache占用情况; expect:缓存信息正确----'
        self.log.info(step_txt)
        step_txt = '----step7.1:查看gs_gsc_memory_detail占用情况; ' \
                   'expect:指定库结果等于1，每个库查询结果小于步骤5-----'
        self.log.info(step_txt)
        check_result7_1 = self.check_db_cache(check_sql1)
        check_db_list7_1 = check_result7_1[0]
        check_db_cache7_1 = check_result7_1[1]
        self.assertEqual(len(check_db_list7_1), len(check_db_list5_1),
                         '执行失败:' + step_txt)
        for i in check_db_list7_1:
            self.assertLess(check_db_cache7_1[i], check_db_cache5_1[i],
                            '执行失败:' + step_txt)

        step_txt = '----step7.2:查看gs_gsc_dbstat_info占用情况; ' \
                   'expect:查询结果包含0库和指定库，每个库查询结果小于步骤5----'
        self.log.info(step_txt)
        check_result7_2 = self.check_db_cache(check_sql2)
        check_db_list7_2 = check_result7_2[0]
        check_db_cache7_2 = check_result7_2[1]
        self.assertEqual(len(check_db_list7_2), len(check_db_list5_2),
                         '执行失败:' + step_txt)
        for i in check_db_list7_2:
            self.assertLess(check_db_cache7_2[i], check_db_cache5_2[i],
                            '执行失败:' + step_txt)

        step_txt = '----step7.3:查看gs_gsc_table_detail占用情况; ' \
                   'expect:查询结果只有0库或者包含0库和指定库，每个库查询结果小于步骤5----'
        self.log.info(step_txt)
        check_result7_3 = self.check_db_cache(check_sql3)
        check_db_list7_3 = check_result7_3[0]
        check_db_cache7_3 = check_result7_3[1]
        self.assertLessEqual(len(check_db_list7_3), len(check_db_list5_3),
                             '执行失败:' + step_txt)
        for i in check_db_list7_3:
            self.assertLess(check_db_cache7_3[i], check_db_cache5_3[i],
                            '执行失败:' + step_txt)

        step_txt = '----step7.4:查看gs_gsc_catalog_detail占用情况; ' \
                   'expect:查询结果包含0库和指定库，每个库查询结果小于步骤5----'
        self.log.info(step_txt)
        check_result7_4 = self.check_db_cache(check_sql4)
        check_db_list7_4 = check_result7_4[0]
        check_db_cache7_4 = check_result7_4[1]
        self.assertEqual(len(check_db_list7_4), len(check_db_list5_4),
                         '执行失败:' + step_txt)
        for i in check_db_list7_4:
            self.assertLess(check_db_cache7_4[i], check_db_cache5_4[i],
                            '执行失败:' + step_txt)

    def check_db_cache(self, sql):
        """
        :param: sql: 查询对象sql
        :return: 返回数据库与对应查询结果字典
        """
        select_result = self.sh.execut_db_sql(sql)
        self.log.info(select_result)
        result = select_result.splitlines()[2:-1]
        db_list = []
        db_dict = dict()
        for i in result:
            db_dict[i.split('|')[0].strip()] = int(i.split('|')[1].strip())
            db_list.append(f"{i.split('|')[0].strip()}")
        return db_list, db_dict

    def tearDown(self):
        step_txt = '----this is teardown----'
        self.log.info(step_txt)
        step1_txt = '----清理数据库; expect:清理成功----'
        self.log.info(step1_txt)
        drop_cmd = f"drop database if exists {self.db_name};"
        drop_result = self.sh.execut_db_sql(drop_cmd)
        self.log.info(drop_result)

        if self.is_reset_para:
            self.step2_txt = '----恢复参数为初始值并查询; expect:设置成功----'
            self.log.info(self.step2_txt)
            self.msg1 = self.sh.execute_gsguc('set',
                                              self.constant.GSGUC_SUCCESS_MSG,
                                              f"enable_global_syscache "
                                              f"={self.init_para1}")

            self.step3_txt = '----重启数据库生效; expect:重启成功----'
            self.log.info(self.step3_txt)
            self.restart = self.sh.restart_db_cluster()
            self.step4_txt = '----查询数据库状态; expect:状态正常----'
            self.log.info(self.step4_txt)
            status = self.sh.exec_cm_ctl(mode='query', param='-Cv')
            self.log.info(status)
            p_status = status.splitlines()[-1].split('|')[0].split('6001')[-1]
            if 'Primary' in p_status and "cluster_state   : Normal" in status:
                self.log.info('---集群状态正常，无需恢复为初始状态---')
            else:
                recovery = self.sh.exec_cm_ctl(mode='switchover',
                                                   param='-a')
                self.log.info(recovery)
                time.sleep(10)
            self.status_result = self.sh.get_db_cluster_status('status')

        self.log.info(f'----{os.path.basename(__file__)}:end----')
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_result,
                      "执行失败" + step_txt + step1_txt)
        if self.is_reset_para:
            self.assertTrue(self.msg1, '执行失败:' + self.step2_txt)
            self.assertTrue(self.restart, '执行失败:' + self.step3_txt)
            self.assertTrue(self.status_result, '执行失败:' + self.step4_txt)
